package com.rabbitmq.controller;

import com.rabbitmq.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @Auther: liyanhao
 * @Description: 发送消息
 * @Date: 2022/5/12 09:29
 * @Version: v1.0
 */
@Slf4j
@RestController
@RequestMapping("/ttl")
public class SendMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    //开始 发消息
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable String message) {
        System.out.println("当前时间：{"+new Date().toString()+"},发送一条信息给两个TTL队列：{"+ message+"}");
        log.info("当前时间：{},发送一条时长{}毫秒TTL信息给队列QC：{}", new Date().toString(),message);
        rabbitTemplate.convertAndSend("X", "XA", "消息来自TTl为10秒的队列" + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自TTl为20秒的队列" + message);
    }
    //开始发消息
    @GetMapping("/sendExpirationMsg/{msg}/{ttlTime}")
    public void sendMsg(@PathVariable String msg, @PathVariable String ttlTime) {
        log.info("当前时间：{},发送一条时长{}毫秒TTL信息给队列QC：{}", new Date().toString(),ttlTime, msg);
        rabbitTemplate.convertAndSend("X","XC",msg,correlationData -> {
            //发送消息的时候 延迟时长
            correlationData.getMessageProperties().setExpiration(ttlTime);
            return correlationData;
        });
        log.info(" 当前时间：{}, 发送一条时长{} 毫秒 TTL 信息给队列 C:{}", new Date(),ttlTime, msg);
    }
    //发送基于插件的 延迟消息
    @GetMapping("/sendPluginDelayMsg/{msg}/{delayTime}")
    public void sendPluginDelayMsg(@PathVariable String msg, @PathVariable Integer delayTime) {
        log.info("当前时间：{},发送一条延迟{}毫秒给延迟队列delayed.queue：{}", new Date().toString(),delayTime, msg);
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME,DelayedQueueConfig.DELAYED_ROUTING_KEY,msg, correlationData -> {
            //发送消息的时候 延迟时长 单位 ms
            correlationData.getMessageProperties().setDelay(delayTime);
            return correlationData;
        });
        log.info(" 当前时间：{}, 发送一条延迟{} 毫秒 延迟信息给队列 C:{}", new Date(),delayTime, msg);
    }


}

















